// Unit test for updateCoins()

#include "dominion.h"  
#include "dominion_helpers.h"  
#include "rngs.h"  
#include <stdio.h>  
#include <math.h>  
#include <stdlib.h>  
#include <assert.h>

#define MAX_CARD 26

int testUpdateCoins(int numPlayers, struct gameState *g){
    int player, after, bonus, i, j, topCard, card, total;
    int cards[MAX_CARD];
    player = floor(Random() * numPlayers);
    bonus = 0;
    // make sure players have cards
    if(g->handCount[player] == 0){
      for(i = 0 ; i < 5; i++){
        topCard = g->deckCount[player]-1;
        g->hand[player][i] = g->deck[player][topCard];
        g->deckCount[player]--;
        g->handCount[player]++;
      }
    }
    for(i = 0 ; i < MAX_CARD ; i++){
      cards[i] = 0;
    }
    cards[gold] = 3;
    cards[silver] = 2;
    cards[copper] = 1;
    total = 0;
    for(j = 0 ; j < g->handCount[player] ; j++){
      card = floor(Random() * MAX_CARD);
      g->hand[player][j] = card;
    //  printf("Card = %i\n", cards[card]);
      total += cards[card];
    }
    bonus = floor(Random() * 10);
    total += bonus;
  //  printf("Total: %i\n", total);
    updateCoins(player, g, bonus);
    after = g->coins;
  //  printf("After: %i\n", after);

    if(after != total)
      return 0;
    return 1;
}

int main(int argc, char *argv[]) {
  struct gameState g;
  long seed;
  int players, i, j, good, bad, results;
  int k[10] = {adventurer, gardens, great_hall, village, minion, mine, cutpurse, 
           baron, salvager, smithy};
  bad = 0;
  good = 0;
  printf("\nUnit Test 2 -> updateCoins() :\n");
  if(argc < 2){
    printf("Usage: ./unttest2.c [random_seed]\n");
  }
  for (j = 0; j < 1000; j++) {
    for (i = 0; i < sizeof(struct gameState); i++) {
      ((char*)&g)[i] = floor(Random() * 256);
    }        
    // give different seed for every test 
    seed = (long)floor(Random()*(long)argv[1]+j); 
    players = j+2;
    // comment out next 2 lines to see bug
    if(players > 4)
      players = players%3+2; // makes sure num players = 2 to 4
  //  printf("Num players %i\n", players);
    initializeGame(players, k, seed, &g);
    results = testUpdateCoins(players,&g);
  if(results == 1){
  //    printf("Test Passed!\n");
      good++;
    }
    else{
  //    printf("Test Failed!\n");
      bad++;
    }
  //  printf("\n");
  }
  printf("Tests passed = %i\n", good);
  printf("Tests Failed = %i\n", bad);
  return 0;
}